package com.demo.xml.jaxb;

import java.util.ArrayList;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.junit.Test;

import com.demo.xml.jaxb.bean.ObjList;
import com.demo.xml.jaxb.bean.People;
import com.demo.xml.jaxb.bean.TestObj;

/**
 * 生成xml
 * @author chenliang
 *
 */
@SuppressWarnings("restriction")
public class JaxbWriteXml {

	/**
	 * 生成Marshaller 对象 代表一个xml 文档对象
	 * @Description:TODO
	 * @author:chenliang
	 * @time:2018年5月18日 下午3:00:06
	 */
	public static <T> Marshaller getMarshaller(Class<T> c) throws JAXBException {

		JAXBContext context = JAXBContext.newInstance(c);
		Marshaller marshaller = context.createMarshaller();
		// 编码格式
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		// 是否格式化生成的xml串
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		// 是否省略xml头信息（<?xml version="1.0" encoding="gb2312" standalone="yes"?>）
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

		return marshaller;
	}

	/**
	 * 根据对象生成xml
	 * @Description:TODO
	 * @author:chenliang
	 * @time:2018年5月18日 下午3:02:15
	 */
	@Test
	public void object2Xml() throws JAXBException {
		Marshaller marshaller = getMarshaller(People.class);
		People people = new People("001", "灰太狼", 22);
		System.out.println("object2Xml------------");
		//生成xml
		marshaller.marshal(people, System.out);
	}

	/**
	 * 根据 list 生成xml
	 * @Description:TODO
	 * @author:chenliang
	 * @time:2018年5月18日 下午3:02:32
	 */
	@Test
	public void list2Xml() throws JAXBException {
		Marshaller marshaller = getMarshaller(ObjList.class);

		ArrayList<TestObj> list = new ArrayList<TestObj>();
		TestObj testObj1 = new TestObj(111, "灰太狼", new Date());
		TestObj testObj2 = new TestObj(222, "灰太狼", new Date());
		list.add(testObj1);
		list.add(testObj2);

		ObjList objlist = new ObjList();
		objlist.setObjList(list);

		System.out.println("list2Xml------------");
		marshaller.marshal(objlist, System.out);
	}
}
